<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :search.sync="search"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.icRegistration_add" @click="addBtn">新 增</el-button>
        <el-button type="warning" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="" slot="workOrderNoSearch">
        <el-input placeholder="请选择 工单号" readonly="true" v-model="search.workOrderNo">
          <el-button slot="append" icon="el-icon-search" @click="openWorkOrderNoModal"></el-button>
        </el-input>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-edit" size="small" type="text" v-if="permission.icRegistration_edit" @click="editBtn(row)">编辑</el-button>
      </template>
    </avue-crud>
    <el-dialog class="dialog" ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" @close="closeDialog">
      <avue-form
        v-if="showDialog"
        :defaults.sync="defaults"
        ref="formRef"
        v-model="dialogForm"
        :option="dialogOption"
        @submit="handleSubmit"
        @reset-change="handleReset"
      ></avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" size="small" type="primary" v-preventReClick @click="$refs.formRef.submit()">
          <i class="el-icon-circle-plus-outline"></i><span>保 存</span></el-button
        >
        <el-button v-if="dialogTitle === '编辑'" size="small" type="primary" v-preventReClick @click="$refs.formRef.submit()"
          ><i class="el-icon-circle-check"></i><span>修 改</span></el-button
        >
        <el-button size="small" @click="$refs.formRef.resetForm()"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <export-excel
      :visible="exprotVisible"
      :loading="loading"
      :option="option"
      :page="page"
      :data="exportData"
      name="IC登记"
      @selectData="handleSelectData"
      @close="handleClose"
    ></export-excel>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, remove } from '@/api/repair/icRegistration';
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import exportExcel from '@/components/export-excel';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    GlobalModalTemplate,
    exportExcel,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'IS_REGISTERATION',
      defaults: {},
      visibile: false,
      exprotVisible: false,
      exportData: [],
      dialogForm: {
        id: '',
        repairCode: '',
        handlingId: '',
        newPartNo: '',
        newPartName: ''
      },
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 5,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: true,
        editBtn: false,
        delBtn: true,
        selection: true,
        searchSpan: 4,
        labelWidth: 120,
        columnBtn: false,
        column: [
          {
            label: '条码类型',
            prop: 'objectType',
            type: 'select',
            addDisplay: false,
            viewDisplay: false,
            searchOrder: 2,
            searchSpan: 6,
            dicData: [
              {
                label: '产品序列号',
                value: 'PRODUCT'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              },
              {
                label: '载具',
                value: 'CARRIER'
              }
            ],
            search: true
          },
          {
            label: '序列号',
            prop: 'productSn',
            addDisplay: false,
            searchSpan: 6,
            search: true
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            formslot: true,
            type: 'search',
            addDisplay: false,
            searchSpan: 6,
            searchOrder: 1,
            search: true
          },
          {
            label: '产品编码',
            addDisplay: false,
            prop: 'productPartNo'
          },
          {
            label: '产品名称',
            addDisplay: false,
            prop: 'productPartName'
          },
          {
            label: '维修站',
            addDisplay: false,
            type: 'select',
            searchSpan: 6,
            prop: 'centerName',
            props: {
              label: 'name',
              value: 'name'
            },
            dicUrl: '/api/mes-product/mro/operatingcenter/list',
            search: true
          },
          {
            label: '维修执行人',
            addDisplay: false,
            prop: 'operatorName'
          },
          {
            label: '维修代码',
            addDisplay: false,
            searchSpan: 6,
            type: 'select',
            prop: 'repairCode',
            props: {
              label: 'code',
              value: 'code'
            },
            dicUrl: '/api/mes-product/mro/dict/list?dictType=ACTION',
            search: true
          },
          {
            label: 'IC名称',
            prop: 'newPartName',
            searchSpan: 6,
            addDisplay: false,
            search: true
          },
          {
            label: '维修开始时间',
            prop: 'startTime',
            addDisplay: false
          },
          {
            label: '维修结束时间',
            addDisplay: false,
            prop: 'endTime'
          }
        ]
      },
      data: [],
      modalName: '', //打开的模态框名称
      showDialog: false,
      dialogTitle: '新增',
      dialogOption: {
        submitBtn: true,
        emptyBtn: true,
        labelWidth: '125',
        column: [
          {
            label: '选择维修记录',
            prop: 'repairCode',
            type: 'search',
            span: 12,
            appendClick: () => {
              this.openRepairListModal();
            },
            rules: [
              {
                required: true,
                message: '请选择维修记录',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '选择IC',
            prop: 'newPartName',
            type: 'search',
            span: 12,
            appendClick: () => {
              this.openIc();
            },
            rules: [
              {
                required: true,
                message: '请选择IC',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime()
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.icRegistration_add, false),
        viewBtn: this.vaildData(this.permission.icRegistration_view, false),
        delBtn: this.vaildData(this.permission.icRegistration_delete, false),
        editBtn: this.vaildData(this.permission.icRegistration_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.objectType == 'PRODUCT' || params.objectType == 'PACKING') {
        params.objectType = 'PRODUCT';
      }
      if (params.objectType == 'CARRIER') {
        params.objectType = 'CARRIER';
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.exportData = this.data;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
    },
    editBtn(row) {
      this.showDialog = true;
      let rowData = structuredClone(row);
      this.dialogForm.repairCode = rowData.repairCode;
      this.dialogForm.newPartName = rowData.newPartName;
      this.dialogForm.newPartNo = rowData.newPartNo;
      this.dialogForm.handlingId = rowData.handlingId;
      this.dialogForm.id = rowData.id;
      this.dialogTitle = '编辑';
    },
    closeDialog() {
      this.dialogForm.repairCode = '';
      this.dialogForm.newPartName = '';
      this.dialogForm.newPartNo = '';
      this.dialogForm.handlingId = '';
      this.dialogForm.id = '';
      this.$refs.formRef && this.$refs.formRef.resetFields();
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    handleSubmit(form, done) {
      if (form.id) {
        add({
          id: form.id,
          handlingId: form.handlingId,
          newPartNo: form.newPartNo,
          newPartName: form.newPartName
        })
          .then(() => {
            done();
            this.$message.success('IC登记编辑成功');
            this.$refs && this.$refs.formRef && this.$refs.formRef.resetForm();
            this.showDialog = false;
            this.onLoad(this.page);
          })
          .catch(() => {
            done();
          });
      } else {
        add({
          handlingId: form.handlingId,
          newPartNo: form.newPartNo,
          newPartName: form.newPartName
        })
          .then(() => {
            done();
            this.$message.success('IC登记新增成功');
            this.$refs && this.$refs.formRef && this.$refs.formRef.resetForm();
            this.showDialog = false;
            this.onLoad(this.page);
          })
          .catch(() => {
            done();
          });
      }
    },
    handleReset() {
      this.showDialog = false;
    },
    // 打开顶部搜索工单号
    openWorkOrderNoModal() {
      this.visibile = true;
      this.modalName = 'searchWorkOrderModal';
      this.tableOption = {
        modalTitle: '选择工单号（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        templateName: 'WORKORDER'
      };
    },
    // 打开维修列表弹框
    openRepairListModal() {
      this.visibile = true;
      this.modalName = 'repairListModal';
      console.log('this.dialogForm', this.dialogForm);
      this.tableOption = {
        modalTitle: '选择维修记录（双击进行选择）',
        width: '80%',
        url: '/api/mes-product/mro/centerproduct/repair/page',
        isPage: true,
        rowSelectionType: 'single',
        searchLabelWidth: 100,
        templateName: 'REPAIRLIST'
      };
    },
    // 打开IC物料列表弹框
    openIc() {
      this.visibile = true;
      this.modalName = 'partmasterModal';
      this.tableOption = {
        modalTitle: '选择物料信息（双击进行选择）',
        url: '/api/mes-admin/part-master/page',
        isPage: true,
        query: {
          semifinished: false //   true 在制品（半成品，成品） false 原材料
        },
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        templateName: 'PARTMASTER'
      };
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'searchWorkOrderModal':
          this.search.workOrderNo = this._get(rowData, 'orderNo', '');
          break;
        case 'repairListModal':
          this.dialogForm.repairCode = this._get(rowData, 'repairCode', '');
          this.dialogForm.handlingId = this._get(rowData, 'productHandlingId', '');
          break;
        case 'partmasterModal':
          this.dialogForm.newPartNo = this._get(rowData, 'partNo', '');
          this.dialogForm.newPartName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    handleSelectData(val) {
      let current = 1;
      let pageSize = this.page.pageSize;
      if (val === 'all') {
        // 接口返回上限500条数据
        pageSize = 500;
      } else {
        current = this.page.currentPage;
      }
      const page = {
        current,
        pageSize
      };
      this.onLoad(page);
    },
    handleExport() {
      this.exportData = this.data;
      this.exprotVisible = true;
    },
    handleClose(val) {
      this.exprotVisible = false;
      this.data = this.exportData.splice(0, this.page.pageSize);
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog ::v-deep .avue-form__menu {
  display: none;
}
::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}
::v-deep .el-dialog__footer {
  border-top: 1px solid #f0f0f0;
  padding: 10px 16px;
}
</style>
